using System;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Net.Http;
using Newtonsoft.Json.Linq;

namespace PddWebAuto.SmsHandler
{
    internal class SmsApi : ISMSAPI
    {
        private string _Error_ = "";
        private readonly string _sid_ = "243";
        private string _token_;

        public bool IsIsLogin { get; private set; }

        public async Task<string> GetPhone(int ReNum = 5)
        {
            var X = 0;
            while (X < ReNum && IsIsLogin)
            {
                var Code = Send("/sms/api/getPhone?token=" + _token_ + "&sid=" + _sid_);
                if (Code.code == 0)
                {
                    return (string)Code.Json["phone"];
                }
                if (Code.code == -1)
                {
                    await TaskHelper.Delay(11 * 1000);
                }
                else
                {
                    break;
                }
                X++;
            }

            return "";
        }

        public async Task<string> WaitSms(int Second, params string[] Args)
        {
            var _time = DateTime.Now;
            string Sms = null;
            var phone = Args[0];
            do
            {
                await TaskHelper.Delay(11 * 1000);
                if ((DateTime.Now - _time).TotalSeconds >= Second)
                {
                    _Error_ = "获取超时";
                    break;
                }

                var Code = Send("/sms/api/getMessage?token=" + _token_ + "&sid=" + _sid_ + "&phone=" + phone);
                if (Code.code == 0)
                {
                    Sms = (string)Code.Json["sms"];
                    Sms = Regex.Match(Sms, "验证码是([0-9]*)")?.Groups[1]?.Value ?? "";
                }
                else if (Code.code == -1 || Code.code == -4)
                {
                    await TaskHelper.Delay(11 * 1000);
                }
                else
                {
                    break;
                }
            } while (string.IsNullOrEmpty(Sms));

            AddBlacklist(phone);
            return Sms ?? "";
        }

        public string GetMsg()
        {
            return _Error_;
        }

        public bool IsUse()
        {
            throw new NotImplementedException();
        }

        public string Login(string Name, string Pass)
        {
            //"api-8elxZRdV"
            //"qq123456"
            var Code = Send("/sms/api/login?username=" + Name + "&password=" + Pass);

            if (Code.code == 0)
            {
                _token_ = (string)Code.Json["token"];
                IsIsLogin = true;
                return "OK";
            }

            return Code.msg;
        }

        /// <summary>
        ///     黑名单
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public bool AddBlacklist(string phone)
        {
            var Code = Send("/sms/api/addBlacklist?token=" + _token_ + "&sid=" + _sid_ + "&phone=" + phone);
            return Code.code == 0;
        }

        public ApiCode Send(string Path)
        {
            _Error_ = "";
            var Item = new HttpItem();
            Item.Method = "GET";
            Item.Accept =
                "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9";
            Item.URL = "http://api.lxy8.net" + Path;
            Item.Timeout = 5 * 1000;
            Item.ContentType = null;
            var Res = Item.Send();
            if (Res.IsSuccessStatusCode)
            {
                try
                {
                    var Json = JObject.Parse(Res.Html);
                    var m = Json.ToObject<ApiCode>();
                    m.Json = Json;
                    if (m.code == 401)
                    {
                        IsIsLogin = false;
                    }

                    if (m.code != 0)
                    {
                        _Error_ = m.msg;
                    }

                    return m;
                }
                catch (Exception)
                {
                    _Error_ = "解析异常";
                    return new ApiCode { code = -999, msg = "解析异常" };
                }
            }

            _Error_ = "网络错误";
            return new ApiCode { code = -999, msg = "网络错误" };
        }

        [Obfuscation(Exclude = true, ApplyToMembers = true)]
        public class ApiCode
        {
            public string msg { set; get; }
            public int code { set; get; }
            public JObject Json { set; get; }
        }
    }
}